package com.derive.education_service.web.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.derive.education_service.common.global.ResponseMessage;
import com.derive.education_service.entity.Admin;
import com.derive.education_service.mapper.AdminMapper;
import com.derive.education_service.utils.VerifyCode;
import com.derive.education_service.web.admin.bean.vo.AdminInfoVo;
import com.derive.education_service.web.admin.service.AdminLoginService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;

/**
 * 管理员登录权限校验
 */
@Service
@Slf4j
public class AdminLoginServiceImpl implements AdminLoginService {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private VerifyCode verifyCode;

    /**
     * 管理员登录
     * -- 暂时使用明文，后面使用密文
     * @param account
     * @param password
     * @return
     */
    @Override
    public ResponseMessage adminLogin(HttpServletRequest request,HttpServletResponse response, String account, String password, String code) {
        HttpSession session = request.getSession();
        Cookie[] cookies = request.getCookies();
        String c = "";
        for (Cookie cookie: cookies) {
            if (cookie.getName().equals("verify")) {
                c = cookie.getValue();
            }
        }
        // 校验验证码
        if (!(c.toLowerCase()).equals(code.toLowerCase())) {
            return ResponseMessage.createByErrorMessage("验证码错误");
        }

        // 执行登录校验信息
        AdminInfoVo adminInfoVo = adminMapper.adminLogin(account, password);

        // 校验账号
        if (adminInfoVo == null) {
            QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("account", account);
            Admin admin = adminMapper.selectOne(queryWrapper);
            if (admin != null) {
                int codef = admin.getLoginFailure();
                admin.setLoginFailure(codef + 1);
                adminMapper.updateById(admin);
            }
            return ResponseMessage.createByErrorMessage("用户账号密码异常");
        }

        // 校验用户状态
        if (!adminInfoVo.getIsState()) {
            return ResponseMessage.createByErrorMessage("用户已失效，请联系管理员");
        }

        // 校验用户登录失败次数是否锁定
        if (adminInfoVo.getLoginFailure() >= 3) {
            // 超过3次为锁定
            return ResponseMessage.createByErrorMessage("用户登录失败次数超过三次，已锁定，请联系管理员");
        }

        // 登录成功，将信息保存到session中 -- 保证会话唯一
        session.setAttribute(session.getId(), adminInfoVo);
        session.setMaxInactiveInterval(900); // 单位是s，15分钟误操作后session自动失效
        response.setHeader("USESSIONID", session.getId()); // 设置到响应的headers中
        return ResponseMessage.createBySuccess("登录成功", adminInfoVo);
    }

    /**
     * 获取验证码
     * @param request
     * @return
     */
    @SneakyThrows
    @Override
    public void getVerifyCode(HttpServletRequest request, HttpServletResponse response) {
        BufferedImage image = verifyCode.getImage();
        String code = verifyCode.getText();

        // 保存在cookie中
        Cookie cookie = new Cookie("verify", code);
        response.addCookie(cookie);
        verifyCode.output(image, response.getOutputStream()); //把图片写到指定流中
    }

    /**
     * 退出登录，注销登录
     * @param request
     * @return
     */
    @Override
    public ResponseMessage adminLogout(HttpServletRequest request) {
        HttpSession session = request.getSession();
        session.invalidate(); // 直接杀死会话
        return ResponseMessage.createBySuccessMessage("注销登录");
    }

    /**
     * 检查用户是否存在
     * @param account
     * @return
     */
    @Override
    public ResponseMessage checkAdmin(String account) {
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account", account);

        Admin admin = adminMapper.selectOne(queryWrapper);
        if (admin == null) {
            return ResponseMessage.createByErrorMessage("用户不存在");
        } else {
            return ResponseMessage.createBySuccessMessage("存在用户");
        }
    }
}
